<template>
  <view class="production-report-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-cyan" :isBack="true">
      <block slot="content">生产报表</block>
      <block slot="right">
        <text class="cuIcon-share" @click="exportReport"></text>
      </block>
    </cu-custom>

    <!-- 时间筛选 -->
    <view class="time-filter margin-top bg-white">
      <view class="filter-header padding">
        <text class="filter-title">时间范围</text>
      </view>
      <view class="time-range padding">
        <view class="time-item">
          <text class="time-label">开始时间</text>
          <picker mode="date" 
                  :value="timeRange.startDate" 
                  @change="onStartDateChange">
            <view class="time-picker">
              {{ timeRange.startDate || '选择日期' }}
              <text class="cuIcon-calendar"></text>
            </view>
          </picker>
        </view>
        <view class="time-item">
          <text class="time-label">结束时间</text>
          <picker mode="date" 
                  :value="timeRange.endDate" 
                  @change="onEndDateChange">
            <view class="time-picker">
              {{ timeRange.endDate || '选择日期' }}
              <text class="cuIcon-calendar"></text>
            </view>
          </picker>
        </view>
      </view>
      <view class="quick-filters padding-lr">
        <view class="quick-filter-list">
          <view v-for="filter in quickFilters" :key="filter.value"
                class="quick-filter-item" 
                :class="{ active: currentQuickFilter === filter.value }"
                @click="selectQuickFilter(filter.value)">
            {{ filter.label }}
          </view>
        </view>
      </view>
    </view>

    <!-- 生产概览 -->
    <view class="production-overview margin-top bg-white">
      <view class="overview-header padding">
        <text class="overview-title">生产概览</text>
      </view>
      <view class="overview-stats padding">
        <view class="stats-grid">
          <view class="stat-card">
            <view class="stat-number text-blue">{{ reportData.totalPlans }}</view>
            <view class="stat-label">生产计划</view>
          </view>
          <view class="stat-card">
            <view class="stat-number text-green">{{ reportData.completedTasks }}</view>
            <view class="stat-label">完成任务</view>
          </view>
          <view class="stat-card">
            <view class="stat-number text-orange">{{ reportData.totalProducts }}</view>
            <view class="stat-label">生产产品</view>
          </view>
          <view class="stat-card">
            <view class="stat-number text-purple">{{ reportData.qualityRate }}%</view>
            <view class="stat-label">合格率</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 效率分析 -->
    <view class="efficiency-analysis margin-top bg-white">
      <view class="analysis-header padding">
        <text class="analysis-title">效率分析</text>
      </view>
      <view class="efficiency-chart padding">
        <view class="chart-placeholder">
          <text class="cuIcon-chart text-gray" style="font-size: 80rpx;"></text>
          <view class="text-gray margin-top-sm">生产效率趋势图</view>
        </view>
      </view>
      <view class="efficiency-metrics padding">
        <view class="metrics-grid">
          <view class="metric-item">
            <view class="metric-value text-green">{{ reportData.avgEfficiency }}%</view>
            <view class="metric-label">平均效率</view>
          </view>
          <view class="metric-item">
            <view class="metric-value text-blue">{{ reportData.totalHours }}h</view>
            <view class="metric-label">总工时</view>
          </view>
          <view class="metric-item">
            <view class="metric-value text-orange">{{ reportData.avgCycleTime }}min</view>
            <view class="metric-label">平均周期</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 员工绩效 -->
    <view class="employee-performance margin-top bg-white">
      <view class="performance-header padding">
        <text class="performance-title">员工绩效</text>
        <text class="view-all" @click="viewAllPerformance">查看全部</text>
      </view>
      <view class="performance-list">
        <view v-for="employee in reportData.topEmployees" :key="employee.id" 
              class="performance-item padding border-bottom">
          <view class="employee-info flex align-center">
            <image :src="employee.avatar || '/static/images/default-avatar.png'" 
                   class="employee-avatar margin-right"></image>
            <view class="employee-details flex-sub">
              <view class="employee-name">{{ employee.name }}</view>
              <view class="employee-dept text-sm text-gray">{{ employee.department }}</view>
            </view>
            <view class="performance-metrics">
              <view class="metric-row">
                <text class="metric-label text-sm text-gray">完成任务：</text>
                <text class="metric-value text-sm text-blue">{{ employee.completedTasks }}</text>
              </view>
              <view class="metric-row">
                <text class="metric-label text-sm text-gray">效率：</text>
                <text class="metric-value text-sm text-green">{{ employee.efficiency }}%</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 质量分析 -->
    <view class="quality-analysis margin-top bg-white">
      <view class="quality-header padding">
        <text class="quality-title">质量分析</text>
      </view>
      <view class="quality-chart padding">
        <view class="chart-placeholder">
          <text class="cuIcon-check text-gray" style="font-size: 80rpx;"></text>
          <view class="text-gray margin-top-sm">质量趋势图</view>
        </view>
      </view>
      <view class="quality-stats padding">
        <view class="quality-grid">
          <view class="quality-item">
            <view class="quality-number text-green">{{ reportData.passedProducts }}</view>
            <view class="quality-label">合格产品</view>
          </view>
          <view class="quality-item">
            <view class="quality-number text-red">{{ reportData.failedProducts }}</view>
            <view class="quality-label">不合格产品</view>
          </view>
          <view class="quality-item">
            <view class="quality-number text-orange">{{ reportData.reworkProducts }}</view>
            <view class="quality-label">返工产品</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 异常统计 -->
    <view class="exception-statistics margin-top bg-white margin-bottom">
      <view class="exception-header padding">
        <text class="exception-title">异常统计</text>
        <text class="view-details" @click="viewExceptionDetails">详情</text>
      </view>
      <view class="exception-list">
        <view v-for="exception in reportData.topExceptions" :key="exception.type" 
              class="exception-item padding border-bottom">
          <view class="exception-info flex justify-between align-center">
            <view class="exception-type">{{ exception.type }}</view>
            <view class="exception-count text-red">{{ exception.count }}次</view>
          </view>
          <view class="exception-trend margin-top-xs">
            <view class="trend-bar">
              <view class="trend-fill" :style="{ width: exception.percentage + '%' }"></view>
            </view>
            <text class="trend-text text-sm text-gray">占比 {{ exception.percentage }}%</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import mesApi from '../../../api/mes'

export default {
  data() {
    return {
      timeRange: {
        startDate: '',
        endDate: ''
      },
      currentQuickFilter: 'week',
      quickFilters: [
        { label: '今日', value: 'today' },
        { label: '本周', value: 'week' },
        { label: '本月', value: 'month' },
        { label: '本季', value: 'quarter' }
      ],
      reportData: {
        totalPlans: 0,
        completedTasks: 0,
        totalProducts: 0,
        qualityRate: 0,
        avgEfficiency: 0,
        totalHours: 0,
        avgCycleTime: 0,
        topEmployees: [],
        passedProducts: 0,
        failedProducts: 0,
        reworkProducts: 0,
        topExceptions: []
      }
    }
  },

  onLoad() {
    this.initTimeRange()
    this.loadReportData()
  },

  onPullDownRefresh() {
    this.loadReportData().then(() => {
      uni.stopPullDownRefresh()
    })
  },

  methods: {
    initTimeRange() {
      const today = new Date()
      const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
      
      this.timeRange.endDate = this.formatDate(today)
      this.timeRange.startDate = this.formatDate(weekAgo)
    },

    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    onStartDateChange(e) {
      this.timeRange.startDate = e.detail.value
      this.loadReportData()
    },

    onEndDateChange(e) {
      this.timeRange.endDate = e.detail.value
      this.loadReportData()
    },

    selectQuickFilter(value) {
      this.currentQuickFilter = value
      this.setQuickTimeRange(value)
      this.loadReportData()
    },

    setQuickTimeRange(value) {
      const today = new Date()
      let startDate = new Date()

      switch (value) {
        case 'today':
          startDate = new Date(today)
          break
        case 'week':
          startDate = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
          break
        case 'month':
          startDate = new Date(today.getFullYear(), today.getMonth(), 1)
          break
        case 'quarter':
          const quarterStart = Math.floor(today.getMonth() / 3) * 3
          startDate = new Date(today.getFullYear(), quarterStart, 1)
          break
      }

      this.timeRange.startDate = this.formatDate(startDate)
      this.timeRange.endDate = this.formatDate(today)
    },

    async loadReportData() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const response = await mesApi.report.getProductionReport({
          startDate: this.timeRange.startDate,
          endDate: this.timeRange.endDate
        })
        
        this.reportData = response.data
        
      } catch (error) {
        console.error('加载报表失败:', error)
        this.loadMockData()
      } finally {
        uni.hideLoading()
      }
    },

    loadMockData() {
      this.reportData = {
        totalPlans: 25,
        completedTasks: 180,
        totalProducts: 1250,
        qualityRate: 96.5,
        avgEfficiency: 85.2,
        totalHours: 1680,
        avgCycleTime: 45,
        topEmployees: [
          {
            id: 1,
            name: '张三',
            department: '生产部',
            avatar: '',
            completedTasks: 28,
            efficiency: 95
          },
          {
            id: 2,
            name: '李四',
            department: '生产部',
            avatar: '',
            completedTasks: 25,
            efficiency: 88
          },
          {
            id: 3,
            name: '王五',
            department: '生产部',
            avatar: '',
            completedTasks: 22,
            efficiency: 92
          }
        ],
        passedProducts: 1206,
        failedProducts: 44,
        reworkProducts: 18,
        topExceptions: [
          {
            type: '设备故障',
            count: 12,
            percentage: 40
          },
          {
            type: '质量问题',
            count: 8,
            percentage: 27
          },
          {
            type: '材料缺失',
            count: 6,
            percentage: 20
          },
          {
            type: '其他异常',
            count: 4,
            percentage: 13
          }
        ]
      }
    },

    viewAllPerformance() {
      uni.navigateTo({
        url: '/pages/production/report/performance'
      })
    },

    viewExceptionDetails() {
      uni.navigateTo({
        url: '/pages/production/report/exceptions'
      })
    },

    exportReport() {
      uni.showActionSheet({
        itemList: ['导出PDF', '导出Excel', '分享报表'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              this.exportPDF()
              break
            case 1:
              this.exportExcel()
              break
            case 2:
              this.shareReport()
              break
          }
        }
      })
    },

    async exportPDF() {
      try {
        uni.showLoading({ title: '导出中...' })
        
        // 模拟导出
        setTimeout(() => {
          uni.hideLoading()
          uni.showToast({
            title: '导出成功',
            icon: 'success'
          })
        }, 2000)
        
      } catch (error) {
        uni.showToast({
          title: '导出失败',
          icon: 'none'
        })
      }
    },

    async exportExcel() {
      try {
        uni.showLoading({ title: '导出中...' })
        
        // 模拟导出
        setTimeout(() => {
          uni.hideLoading()
          uni.showToast({
            title: '导出成功',
            icon: 'success'
          })
        }, 2000)
        
      } catch (error) {
        uni.showToast({
          title: '导出失败',
          icon: 'none'
        })
      }
    },

    shareReport() {
      uni.share({
        provider: 'weixin',
        type: 0,
        title: '生产报表',
        summary: `${this.timeRange.startDate} 至 ${this.timeRange.endDate} 生产报表`,
        success: () => {
          uni.showToast({
            title: '分享成功',
            icon: 'success'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.production-report-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.time-filter {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .filter-header {
    border-bottom: 1rpx solid #f0f0f0;
    
    .filter-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .time-range {
    display: flex;
    gap: 24rpx;
    
    .time-item {
      flex: 1;
      
      .time-label {
        display: block;
        font-size: 24rpx;
        color: #666;
        margin-bottom: 16rpx;
      }
      
      .time-picker {
        height: 80rpx;
        padding: 0 24rpx;
        border: 1rpx solid #d9d9d9;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 28rpx;
        color: #333;
      }
    }
  }
  
  .quick-filters {
    .quick-filter-list {
      display: flex;
      gap: 16rpx;
      
      .quick-filter-item {
        padding: 12rpx 24rpx;
        border-radius: 20rpx;
        background-color: #f0f0f0;
        color: #666;
        font-size: 24rpx;
        
        &.active {
          background-color: #1890ff;
          color: white;
        }
      }
    }
  }
}

.production-overview {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .overview-header {
    border-bottom: 1rpx solid #f0f0f0;
    
    .overview-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24rpx;
    
    .stat-card {
      text-align: center;
      padding: 24rpx;
      background-color: #fafafa;
      border-radius: 8rpx;
      
      .stat-number {
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.efficiency-analysis,
.quality-analysis {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .analysis-header,
  .quality-header {
    border-bottom: 1rpx solid #f0f0f0;
    
    .analysis-title,
    .quality-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .chart-placeholder {
    text-align: center;
    padding: 60rpx 0;
    background-color: #fafafa;
    border-radius: 8rpx;
  }
  
  .efficiency-metrics,
  .quality-stats {
    .metrics-grid,
    .quality-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 24rpx;
      
      .metric-item,
      .quality-item {
        text-align: center;
        
        .metric-value,
        .quality-number {
          font-size: 32rpx;
          font-weight: bold;
          margin-bottom: 8rpx;
        }
        
        .metric-label,
        .quality-label {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }
}

.employee-performance {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .performance-header {
    border-bottom: 1rpx solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .performance-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .view-all {
      font-size: 24rpx;
      color: #1890ff;
    }
  }
  
  .performance-item {
    .employee-avatar {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
    }
    
    .employee-name {
      font-size: 28rpx;
      font-weight: bold;
      margin-bottom: 4rpx;
    }
    
    .performance-metrics {
      text-align: right;
      
      .metric-row {
        margin-bottom: 4rpx;
        
        .metric-label {
          margin-right: 8rpx;
        }
      }
    }
  }
}

.exception-statistics {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .exception-header {
    border-bottom: 1rpx solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .exception-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .view-details {
      font-size: 24rpx;
      color: #1890ff;
    }
  }
  
  .exception-item {
    .exception-type {
      font-size: 28rpx;
      color: #333;
    }
    
    .exception-count {
      font-size: 28rpx;
      font-weight: bold;
    }
    
    .exception-trend {
      display: flex;
      align-items: center;
      gap: 16rpx;
      
      .trend-bar {
        flex: 1;
        height: 8rpx;
        background-color: #f0f0f0;
        border-radius: 4rpx;
        overflow: hidden;
        
        .trend-fill {
          height: 100%;
          background-color: #f5222d;
        }
      }
      
      .trend-text {
        white-space: nowrap;
      }
    }
  }
}
</style>
